<?php

namespace app\admin\controller;

use classes\RedisClass;
use classes\TokenBucket;
use controller\BasicAdmin;
use service\DataService;
use service\ToolsService;
use think\Db;
use think\exception\HttpResponseException;
use think\facade\Cache;
use think\facade\Log;

/**
 * 项目管理
 */
class Info extends BasicAdmin
{

    public $info = 'tp_vote_item';
    public $cate = 'tp_vote_cate';
    public $source = 'tp_source';
    public $region = 'tp_region';
    public $sale_area = 'tp_sale_area';

    /**
     * 项目列表
     * @return array|string
     */
    public function lists()
    {
        $this->title = '项目管理';
        $get = $this->request->get();
        $db = Db::name($this->info)
            ->alias('a')
            ->join($this->cate . ' b', 'b.cate_id=a.cate_id', 'left')
            ->join($this->source . ' c', 'c.tag=a.source', 'left')
            ->join($this->region . ' d', 'd.id=a.province_id', 'left')
            ->join($this->region . ' e', 'e.id=a.city_id', 'left')
            ->join($this->sale_area . ' f', 'f.id=a.sub_cate_id', 'left')
            ->field('a.*,b.name cate_name,c.name source_name,d.name province_name,e.name city_name,f.name sale_area_name')
            ->where('a.cate_id<3');
//            ->where(['a.is_deleted' => '0']);

        foreach (['id', 'item', 'sub_item', 'phone', 'sub_item2', 'address'] as $field) {
            if (isset($get[$field]) && $get[$field] !== '') {
                $value = trim($get[$field]);
                $db->whereLike('a.' . $field, "%{$value}%");
            }
        }
        foreach (['status', 'cate_id', 'sub_cate_id', 'province_id', 'city_id', 'is_use', 'source'] as $field) {
            if (isset($get[$field]) && $get[$field] !== '') {
                $value = trim($get[$field]);
                $db->where('a.' . $field, "{$value}");
            }
        }
        //赛区

//        $cates = Db::name('tp_vote_cate')
//            ->where('pid', 0)
//            ->order('sort desc,cate_id asc')
//            ->select();
//
//
//        //经销商
//        $jxs_list = Db::name('tp_vote_cate')
//            ->cache('jxs_list')
//            ->where('pid > 0')
//            ->order('sort desc,cate_id asc')
//            ->select();
//
//        //业务区域
//        $sale_area_list = Db::name('tp_sale_area')
//            ->cache('sale_area_list')
//            ->field('id,name')
//            ->order('id desc')
//            ->select();
//
//        $province_list = Db::name('tp_region')
//            ->field('id province_id,name')
//            ->where('parent_id', 0)
//            ->order('id asc')
//            ->cache('province_list')
//            ->select();
//
//        $city_list = [];
//        if (isset($get['province_id']) && $get['province_id'] !== '') {
//            $city_list = Db::name('tp_region')
//                ->field('id city_id,name')
//                ->where('parent_id', $get['province_id'])
//                ->order('id asc')
//                ->select();
//        }
//
//        if (isset($get['video_status']) && $get['video_status'] !== '') {
//            if ($get['video_status'] == 1) {
//                $db->whereLike('a.videourl', "%jtyhvideo%");
//            } elseif ($get['video_status'] == 0) {
//                $db->where('a.videourl = ""');
//            }
//        }
//
//        if (isset($get['reg_status']) && $get['reg_status'] !== '') {
//            if ($get['reg_status'] == 1) {
//                $db->where('a.wechat_id = ""');
//            } elseif ($get['reg_status'] == 0) {
//                $db->whereLike('a.wechat_id', "%o6rBgx%");
//            }
//        }


//        $this->assign('jxs_list', $jxs_list);
//        $this->assign('cates1', $cates);
//        $this->assign('sale_area_list', $sale_area_list);
//        $this->assign('province_list', $province_list);
//        $this->assign('city_list', $city_list);

        $sessin_user = session('user');
        if ($sessin_user['cate_id'] > 0) {
            $db = $db->where(['a.cate_id' => $sessin_user['cate_id']]);
        }

        foreach (['addtime'] as $field) {
            if (isset($get[$field]) && $get[$field] !== '') {
                list($start, $end) = explode(' - ', $get[$field]);
                $db->whereTime($field, ["{$start} 00:00:00", "{$end} 23:59:59"]);
            }
        }

//        $order = 'a.updatetime desc,a.id desc';
        $order = 'a.id desc';
        if (isset($get['sort_by_vcount']) && $get['sort_by_vcount'] !== '') {
            if ($get['sort_by_vcount'] == 'desc') {
                $order = 'a.vcount desc';
            } else {
                $order = 'a.vcount asc';
            }
        }


        return parent::_list($db->order($order), 'id');
    }


    //根据省份id获取城市
    public function get_city()
    {
        $province_id = $this->request->post('province_id');
        $list = Db::name('tp_region')
            ->field('id city_id,name')
            ->where('parent_id', $province_id)
            ->order('sort desc')
            ->select();

        $opt = '';
        foreach ($list as $key => $val) {
            $opt .= "<option value='{$val['city_id']}'>{$val['name']}</option>";
        }
        return json($opt);
    }


    //根城市id获取城区
    public function get_district()
    {
        $city_id = $this->request->post('city_id');
        if ($city_id == 0) {
            return json('');
        }
        $list = Db::name('tp_region')
            ->field('id district_id,name')
            ->where('parent_id', $city_id)
            ->order('sort desc')
            ->cache('region_' . $city_id)
            ->select();

        $opt = '';
        foreach ($list as $key => $val) {
            $opt .= "<option value='{$val['district_id']}'>{$val['name']}</option>";
        }
        return json($opt);
    }

    //导出数据
    public function outItems()
    {
        $get = input();

        $db = Db::name($this->info)
            ->alias('a')
            ->join($this->cate . ' b', 'b.cate_id=a.cate_id', 'left')
            ->field('a.id,a.item,b.name cate_name,a.info,a.phone,a.address')
            ->where('a.cate_id<3');
//            ->where(['a.is_deleted' => '0']);

        foreach (['id', 'item', 'sub_item', 'phone', 'sub_item2', 'address'] as $field) {
            if (isset($get[$field]) && $get[$field] !== '') {
                $value = trim($get[$field]);
                $db->whereLike('a.' . $field, "%{$value}%");
            }
        }
        foreach (['status', 'cate_id', 'sub_cate_id', 'province_id', 'city_id', 'is_use', 'source'] as $field) {
            if (isset($get[$field]) && $get[$field] !== '') {
                $value = trim($get[$field]);
                $db->where('a.' . $field, "{$value}");
            }
        }

        foreach (['addtime'] as $field) {
            if (isset($get[$field]) && $get[$field] !== '') {
                list($start, $end) = explode(' - ', $get[$field]);
                $db->whereTime($field, ["{$start} 00:00:00", "{$end} 23:59:59"]);
            }
        }

        if (isset($get['video_status']) && $get['video_status'] !== '') {
            if ($get['video_status'] == 1) {
                $db->whereLike('a.videourl', "%jtyhvideo%");
            } elseif ($get['video_status'] == 0) {
                $db->where('a.videourl = ""');
            }
        }

        if (isset($get['reg_status']) && $get['reg_status'] !== '') {
            if ($get['reg_status'] == 1) {
                $db->where('a.wechat_id = ""');
            } elseif ($get['reg_status'] == 0) {
                $db->whereLike('a.wechat_id', "%o6rBgx%");
            }
        }

        $title = '全部';

        $order = 'a.vcount desc,a.id asc';
        if (isset($get['sort_by_vcount']) && $get['sort_by_vcount'] !== '') {
            if ($get['sort_by_vcount'] == 'desc') {
                $order = 'a.vcount desc';
            } else {
                $order = 'a.vcount asc';
            }
        }

        $db->where([]);
        $db->order($order);
        $data = $db->select();


        $header = array('ID', '姓名', '分类', '身份证', '手机号', '地址',);
        $name = $title . '数据';
        $result = \classes\Excel::writer($header, $data, $name, count($header) - 1);

        if ($result) {
            $this->success('导出成功');
        } else {
            $this->error('导出失败');
        }

    }

    /**
     * 数据处理
     * @param array $data
     */
    protected function _data_filter(&$data)
    {
        $result = $this->buildCateList($data);
        $this->assign([
            'cates' => ToolsService::arr2table($result['cate'], 'cate_id'),
            'sources' => ToolsService::arr2table($result['source'], 'id'),
        ]);
    }


    protected function buildCateList(&$infoList)
    {
        // 产品分类处理
        $cateField = 'cate_id,pid,name';
//        $cateWhere = ['pid' => '0'];
//        $cateWhere = [];
        $cateList = Db::name($this->cate)->where('cate_id<3')->where('pid', 0)->order('sort asc,cate_id asc')->column($cateField);
        $sourceList = Db::name($this->source)->order('id desc')->column('id,name,tag');

        return ['list' => $infoList, 'cate' => $cateList, 'source' => $sourceList];
    }


    /**
     * 添加项目
     * @return array|string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\Exception
     */
    public function add()
    {
        if (!$this->request->isPost()) {
            $this->title = '添加项目';
            $cateField = 'cate_id,pid,name';
            //赛区
            $cates = Db::name($this->cate)->where('pid', 0)->order('sort asc,cate_id asc')->column($cateField);

            $jxs_list = Db::name('tp_vote_cate')
                ->cache('jxs_list')
                ->where('pid > 0')
                ->order('sort desc,cate_id asc')
                ->select();

            $province_list = Db::name('tp_region')
                ->field('id province_id,name')
                ->where('parent_id', 0)
                ->order('id asc')
                ->cache('province_list')
                ->select();

            $city_list = [];

            $sale_area_list = Db::name('tp_sale_area')
                ->cache('sale_area_list')
                ->field('id,name')
                ->order('id desc')
                ->select();

            $this->assign('sale_area_list', $sale_area_list);
            $this->assign('province_list', $province_list);
            $this->assign('city_list', $city_list);
            $this->assign('jxs_list', $jxs_list);
            $this->assign('cates', $cates);
            return $this->_form($this->info, 'form');
        }
        try {
//            $data = $this->_form_build_data();
            $data = $this->request->post();
            Db::transaction(function () use ($data) {
                $data['item'] = $data['sub_item'];
                $data['addtime'] = time();

                if (!$data['sex']) {
                    $this->error('请选择性别！');
                }


                if ($data['cate_id'] == 1) {
                    if (!$data['province_id']) {
                        $this->error('请选择所在省份！');
                    }

                    if (!$data['city_id']) {
                        $this->error('请选择所在城市！');
                    }
                }

                if ($data['cate_id'] == 2) {
                    $data['address'] = $data['info'];
                }


//                if (!$data['sub_cate_id']) {
//                    $this->error('请选择所属经销商！');
//                }

                if (!$data['cate_id']) {
                    $this->error('请选择所属赛区！');
                }

                if (!check_mobile_number($data['phone'])) {
                    $this->error('手机号格式不正确！');
                }

                if (empty($data['startpicurl'])) {
                    $this->error('请上传照片！');
                }
//
//                if (empty($data['startpicurl2'])) {
//                    $this->error('请上传工作照！');
//                }
//
//                if (empty($data['startpicurl3'])) {
//                    $this->error('请上传12月25号内的郎酒销售小票1张！');
//                }

                $reg2 = Db::name('tp_vote_item')->where('phone', $data['phone'])->find();
                if ($reg2) {
                    $this->error('手机号已存在，请勿重复报名！');
                }

                //视频截帧（cos配置工作流）
                $url_arr = explode('http://jtyhvideo.zoudingyong.com', input('videourl'));
                $url_arr = explode('.', $url_arr[1]);
                $small_pic = 'http://jtyhvideo.zoudingyong.com' . $url_arr[0] . '_0.jpg';
                $data['small_pic'] = $small_pic;

                $id = Db::name($this->info)->insertGetId($data);

                //更新报名状态
//                Db::name('tp_sales')->where('mobile', $data['phone'])->setField('is_reg', 1);
            });


        } catch (HttpResponseException $exception) {
            return $exception->getResponse();
        } catch (\Exception $e) {
            $this->error('项目添加失败，请稍候再试！' . $e->getMessage());
        }
        list($base, $spm, $url) = [url('@admin'), $this->request->get('spm'), url('info/lists')];
        $this->success('添加项目成功！', "{$base}#{$url}?spm={$spm}");
    }

    /**
     * 编辑项目
     * @return array|string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function edit()
    {
        if (!$this->request->isPost()) {
            $id = $this->request->get('id');
            $info = Db::name($this->info)->where(['id' => $id])->find();
            empty($info) && $this->error('需要编辑的项目不存在！');
            $cateField = 'cate_id,pid,name';
            //赛区
            $cates = Db::name($this->cate)->where('pid', 0)->order('sort asc,cate_id asc')->column($cateField);

            $jxs_list = Db::name('tp_vote_cate')
                ->cache('jxs_list')
                ->where('pid > 0')
                ->order('sort desc,cate_id asc')
                ->select();

            $province_list = Db::name('tp_region')
                ->field('id province_id,name')
                ->where('parent_id', 0)
                ->order('id asc')
                ->cache('province_list')
                ->select();
            $city_list = Db::name('tp_region')
                ->field('id city_id,name')
                ->where('parent_id', $info['province_id'])
                ->order('id asc')
                ->select();
            $sale_area_list = Db::name('tp_sale_area')
                ->cache('sale_area_list')
                ->field('id,name')
                ->order('id desc')
                ->select();

            $this->assign('sale_area_list', $sale_area_list);
            $this->assign('province_list', $province_list);
            $this->assign('city_list', $city_list);
            $this->assign('jxs_list', $jxs_list);
            $this->assign('cates', $cates);
            return $this->fetch('form', ['vo' => $info, 'title' => '编辑项目']);
        }
        try {
            $data = $this->request->post();
            $id = $this->request->post('id');
            $info = Db::name($this->info)->where(['id' => $id])->find();
            empty($info) && $this->error('编辑项目失败，请稍候再试！');

            Db::transaction(function () use ($data, $id, $info) {
                // 更新产品主表

                $data['item'] = $data['sub_item'];
                $data['updatetime'] = time();//更新时间

                //视频截帧（cos配置工作流）
                $url_arr = explode('http://jtyhvideo.zoudingyong.com', input('videourl'));
                $url_arr = explode('.', $url_arr[1]);
                $small_pic = 'http://jtyhvideo.zoudingyong.com' . $url_arr[0] . '_0.jpg';
                $data['small_pic'] = $small_pic;

                if (!$data['sex']) {
                    $this->error('请选择性别！');
                }


                if ($data['cate_id'] == 1) {
                    if (!$data['province_id']) {
                        $this->error('请选择所在省份！');
                    }

                    if (!$data['city_id']) {
                        $this->error('请选择所在城市！');
                    }
                }

//                if (!$data['sub_cate_id']) {
//                    $this->error('请选择所属经销商！');
//                }

                if (!$data['cate_id']) {
                    $this->error('请选择所属赛区！');
                }

                if (!check_mobile_number($data['phone'])) {
                    $this->error('手机号格式不正确！');
                }

                if (empty($data['startpicurl'])) {
                    $this->error('请上传照片！');
                }

//                if (empty($data['startpicurl2'])) {
//                    $this->error('请上传工作照！');
//                }

//                if (empty($data['startpicurl3'])) {
//                    $this->error('请上传12月25号内的郎酒销售小票1张！');
//                }

                if (empty($data['videourl'])) {
                    $this->error('请上传视频！');
                }

                $where = ['id' => $id];
                unset($data['id']);
                Db::name($this->info)->where($where)->update($data);

            });


            RedisClass::del_item_info($id);
            Cache::store('redis')->handler()->zRem('vote:item_ids', $id); //全部项目
            Cache::store('redis')->handler()->zRem('vote:item_ids' . $info['cate_id'], $id);//分类项目
            Cache::store('redis')->handler()->zRem('vote:score:ids', $id);//全部排名
            Cache::store('redis')->handler()->zRem('vote:score:ids' . $info['cate_id'], $id); //分类排名
            RedisClass::get_redis_item_info($id);

            if ($info['status'] > 0) {
                Cache::store('redis')->handler()->zAdd('vote:item_ids', $info['id'], $info['id']);//全部项目
                Cache::store('redis')->handler()->zAdd('vote:item_ids' . $info['cate_id'], $info['id'], $info['id']);//分类项目
                Cache::store('redis')->handler()->zAdd('vote:score:ids', $info['vcount'], $info['id']);//全部排行
                Cache::store('redis')->handler()->zAdd('vote:score:ids' . $info['cate_id'], $info['vcount'], $info['id']);//分类排名

            }


        } catch (HttpResponseException $exception) {
            return $exception->getResponse();
        } catch (\Exception $e) {
            $this->error('编辑项目失败，请稍候再试！' . $e->getMessage());
        }
        list($base, $spm, $url) = [url('@admin'), $this->request->get('spm'), url('info/lists')];


        $this->success('编辑项目成功！', "{$base}#{$url}?spm={$spm}");
    }


    /**
     * 详情
     * @return array|string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\Exception
     */
    public function detail()
    {

        $id = $this->request->get('id');
        $vo = Db::name($this->info)
            ->alias('a')
            ->join($this->cate . ' b', 'b.cate_id=a.cate_id', 'left')
            ->join($this->source . ' c', 'c.tag=a.source', 'left')
            ->join($this->region . ' d', 'd.id=a.province_id', 'left')
            ->join($this->region . ' e', 'e.id=a.city_id', 'left')
            ->join($this->sale_area . ' f', 'f.id=a.sub_cate_id', 'left')
            ->field('a.*,b.name cate_name,c.name source_name,d.name province_name,e.name city_name,f.name sale_area_name')
            ->find($id);
        $vo['addtime'] = date('Y-m-d H:i:s', $vo['addtime']);
        $vo['checktime'] = date('Y-m-d H:i:s', $vo['checktime']);
        empty($vo) && $this->error('数据不存在！');
        return $this->fetch('detail', ['vo' => $vo, 'title' => '详情']);

    }

    /**
     * 扣除票数
     * @return array|string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function deduct()
    {
        if (!$this->request->isPost()) {
            $id = $this->request->get('id');
            $info = Db::name($this->info)->where(['id' => $id])->find();
            empty($info) && $this->error('需要扣除的项目不存在！');
            return $this->fetch('deduct', ['vo' => $info, 'title' => '扣除票数']);
        }
        try {
            $post = $this->request->post();
            $id = $this->request->post('id');
            $info = Db::name($this->info)->where(['id' => $id])->find();
            empty($info) && $this->error('需要扣除的项目不存在！');

            if ($post['deduct_count'] < 0) {
                $this->error('请输入正数！');
            }
            if ($info['vcount'] - abs($post['deduct_count']) < 0) {
                $this->error('票数不足,无法扣除！');
            }

            Db::transaction(function () use ($post, $id, $info) {
                // 更新产品主表
                $deduct_count = abs($post['deduct_count']);
                $where = ['id' => $id];
                $ret = Db::name($this->info)->where($where)->setDec('vcount', $deduct_count);

                if ($ret) {
                    $info = RedisClass::get_redis_item_info($id);
                    Cache::store('redis')->handler()->ZINCRBY('vote:score:ids', -$deduct_count, $id);//排行榜
                    Cache::store('redis')->handler()->ZINCRBY('vote:score:ids' . $info['cate_id'], -$deduct_count, $id);//分类排名
                    RedisClass::del_item_info($id);
                    Cache::store('redis')->dec('total_vcount', $deduct_count); //总票数减少
                }
            });

        } catch (HttpResponseException $exception) {
            return $exception->getResponse();
        } catch (\Exception $e) {
            $this->error('扣除票数失败，请稍候再试！' . $e->getMessage());
        }
        list($base, $spm, $url) = [url('@admin'), $this->request->get('spm'), url('info/lists')];

        $this->success('扣除票数成功！', "{$base}#{$url}?spm={$spm}");
    }

    /**
     * 增加票数
     * @return array|string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function raise————()
    {
        if (!$this->request->isPost()) {
            $id = $this->request->get('id');
            $info = Db::name($this->info)->where(['id' => $id])->find();
            empty($info) && $this->error('需要增票的项目不存在！');
            return $this->fetch('raise', ['vo' => $info, 'title' => '增加票数']);
        }
        try {
            $post = $this->request->post();
            $id = $this->request->post('id');
            $info = Db::name($this->info)->where(['id' => $id])->find();
            empty($info) && $this->error('需要扣除的项目不存在！');

            if ($post['raise_count'] < 0) {
                $this->error('请输入正数！');
            }

            Db::transaction(function () use ($post, $id, $info) {
                // 更新产品主表
                $raise_count = abs($post['raise_count']);
                $where = ['id' => $id];
                $ret = Db::name($this->info)->where($where)->setInc('vcount', $raise_count);

                if ($ret) {
                    RedisClass::del_item_info($id);
                    RedisClass::get_redis_item_info($id);
                    Cache::store('redis')->handler()->ZINCRBY('vote:score:ids', $raise_count, $id);//排行榜

//                    $config = RedisClass::get_vote_config_info();
                    Cache::store('redis')->inc('total_vcount', $raise_count); //总票数增加
                }
            });

        } catch (HttpResponseException $exception) {
            return $exception->getResponse();
        } catch (\Exception $e) {
            $this->error('增加票数失败，请稍候再试！' . $e->getMessage());
        }
        $this->success('增加票数成功！', "");
    }


    /**
     * 自动刷票数
     * @return array|string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function ticket__()
    {
        if (!$this->request->isPost()) {
            $id = $this->request->get('id');
            $info = Db::name($this->info)->where(['id' => $id])->find();
            empty($info) && $this->error('项目不存在！');
            return $this->fetch('ticket', ['vo' => $info, 'title' => '']);
        }
        try {
            $post = $this->request->post();
            $id = $this->request->post('id');
            $info = Db::name($this->info)->where(['id' => $id])->find();
            empty($info) && $this->error('项目不存在！');

            if ($post['ticket_num'] < 0) {
                $this->error('请输入正数！');
            }

            Db::transaction(function () use ($post, $id, $info) {
                // 更新产品主表
                $where = ['id' => $id];
                $ret = Db::name($this->info)->where($where)->update([
                    'is_auto_ticket' => $post['is_auto_ticket'],
                    'ticket_num' => $post['ticket_num']
                ]);

                if ($ret) {
                    RedisClass::del_item_info($id);
                    RedisClass::get_redis_item_info($id);
                }
            });

        } catch (HttpResponseException $exception) {
            return $exception->getResponse();
        } catch (\Exception $e) {
            $this->error('操作失败，请稍候再试！' . $e->getMessage());
        }
        $this->success('操作成功！', "");
    }

    /**
     * 删除
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function del()
    {
        $item_ids = $this->request->post('id');
        $item_ids = explode(',', $item_ids);

        foreach ($item_ids as $id) {
            $info = Db::name($this->info)->find($id);
            //类型0 前台 1后台 前台自助报名 有openid
//                if ($info['cate_id'] == 0) {
//                    Db::name('tp_lottery_record')
//                        ->where([
//                            'wecha_id' => $info['wechat_id'],
//                            'typeid' => 2,
//                        ])
//                        ->delete();
//
//                    Cache::rm('my_reg_prizes_' . $info['wechat_id']); //删除报名卡券缓存
//                } else {
//                    Db::name('tp_lottery_record')
//                        ->where([
//                            'wecha_id' => $info['phone'],
//                            'typeid' => 2,
//                        ])
//                        ->delete();
//                }

            //删除 其他
            RedisClass::del_item_info($id);
            RedisClass::del_item_info_by_openid($info['wechat_id']);
            Cache::store('redis')->handler()->zRem('vote:item_ids', $id); //全部项目
            Cache::store('redis')->handler()->zRem('vote:item_ids' . $info['cate_id'], $id);//分类项目
            Cache::store('redis')->handler()->zRem('vote:score:ids', $id);//全部排名
            Cache::store('redis')->handler()->zRem('vote:score:ids' . $info['cate_id'], $id); //分类排名

            Db::name($this->info)->where('id', $id)->delete();
        }

        $this->success("删除成功！", '');


    }

    /**
     * 打回审核
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function afresh()
    {
        if (DataService::update($this->info)) {
            $id = $this->request->post('id');
//            $status = $this->request->post('status');

            RedisClass::del_item_info($id);
            Cache::store('redis')->handler()->zRem('vote:item_ids', $id); //全部项目
            Cache::store('redis')->handler()->zRem('vote:item_ids5', $id);//分类项目
            Cache::store('redis')->handler()->zRem('vote:score:ids', $id);//全部排名
            Cache::store('redis')->handler()->zRem('vote:score:ids5', $id); //分类排名

            $this->success("操作成功！", '');
        }
        $this->error("操作失败，请稍候再试！");


    }

    /**
     * 审核
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function check()
    {
        if (DataService::update($this->info)) {
            $id = $this->request->post('id');
            $status = $this->request->post('status');

            $info = Db::name($this->info)->find($id);

            //第一次审核(短信)
            /*try {
                if ($info['checktime'] == 0) {

                    $all_sncode = '';
                    for ($x = 0; $x <= 9; $x++) {
                        $sncode = mt_rand(100000000, 999999999);  //兑奖码

                        $wecha_id = $info['cate_id'] == 0 ? $info['wechat_id'] : $info['phone'];
                        Db::name('tp_lottery_record')->insert(array('typeid' => 2, 'wecha_id' => $wecha_id, 'islottery' => 1, 'sn' => $sncode, 'note' => '99元购酒抵扣券1张', 'time' => time(), 'prize' => 0));
                        $all_sncode .= $sncode . ',';
                    }
                    if ($info['cate_id'] == 1) {
                        $msg = "【郎酒股份】感谢您的参与，您在参加2020'青花郎杯'湖南省摄影大赛中，获得由青花郎提供的报名奖励-价值990元的购酒现金抵扣券:{$all_sncode}";
                        send_sms_to_mobile($info['phone'], $msg);
                    }
                }
            } catch (\Exception $e) {
                Log::error('短信发送失败');
            }*/

            //第一次审核（增加抽奖机会）、后台报名不增加
//            if ($info['checktime'] == 0 && !empty($info['wechat_id'])) {
//                Cache::store('redis')->handler()->LPUSH('lottery:wecha_id:' . $info['wechat_id'], 1);
//            }


//            if ($info['cate_id'] == 1) {
//                Cache::rm('my_reg_prizes_' . $info['wechat_id']); //删除报名卡券缓存
            RedisClass::del_item_info($id);
            RedisClass::get_redis_item_info($id);
            Cache::store('redis')->handler()->zAdd('vote:item_ids', $id, $info['id']);//全部项目
            Cache::store('redis')->handler()->zAdd('vote:item_ids' . $info['cate_id'], $id, $info['id']);//分类项目
            Cache::store('redis')->handler()->zAdd('vote:score:ids', $info['vcount'], $info['id']);//全部排名
            Cache::store('redis')->handler()->zAdd('vote:score:ids' . $info['cate_id'], $info['vcount'], $info['id']);//分类排名
//            }
            Db::name($this->info)->where('id', $id)->update(['checktime' => time()]);

            $this->success("操作成功！", '');
        }
        $this->error("操作失败，请稍候再试！");
    }


    /**
     * 操作
     * @return string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\Exception
     */
    public function operate()
    {
        if (!$this->request->isPost()) {
            $id = $this->request->get('id');
            $data = Db::name($this->info)->find($id);
            $message_list = Db::name('tp_message')->select(); //常用理由
            empty($data) && $this->error('未找到相关数据！');
            return $this->fetch('operate', ['vo' => $data, 'message_list' => $message_list, 'title' => '操作']);
        }
        try {
            $id = $this->request->post('id');
            $checkinfo = $this->request->post('checkinfo');
            $data = Db::name($this->info)->find($id);
            empty($data) && $this->error('未找到相关数据！');
            empty($checkinfo) && $this->error('请输入不通过的原因！');

            Db::name($this->info)->where('id', $id)->update([
                'checktime' => time(),
                'checkinfo' => $checkinfo,
                'status' => -1,
            ]);

            RedisClass::del_item_info($id);
            RedisClass::get_redis_item_info($id);


            //审核状态 -1-审核不通过 0-未审核 1-审核通过 2 锁定
//            if ($status == -1) {
            $msg = "【郎酒股份】您报名参与“郎酒醉美品牌形象店”活动的报名信息审核未通过(原因：{$checkinfo})，请重新提交相关信息！";
            send_sms_to_mobile($data['phone'], $msg);
//            }

        } catch (HttpResponseException $exception) {
            return $exception->getResponse();
        } catch (\Exception $e) {
            $this->error('操作失败，请稍候再试！' . $e->getMessage());
        }
        $this->success('操作成功！', "");
    }

    /**
     * 锁定/解锁
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function clock()
    {
        if (DataService::update($this->info)) {
            $id = $this->request->post('id');
            $info = Db::name($this->info)->find($id);
            $status = $this->request->post('value');
            try {
                if ($status == 2) {
                    $msg = "【大赛组委会】您的参数作品(ID:{$info['id']})异常，已被锁定,有如疑问请联系客服";
                    //send_sms_to_mobile($info['phone'], $msg);
                }
            } catch (\Exception $e) {
                Log::error('短信发送失败');
            }
            RedisClass::del_item_info($id);
            RedisClass::get_redis_item_info($id);
            Cache::store('redis')->rm('vote:lock_hour:item_id:' . $id); //小时锁定缓存
            Cache::store('redis')->rm('vote:lock:item_id:' . $id);//分钟锁定缓存

            $this->success("操作成功！", '');
        }
        $this->error("操作失败，请稍候再试！");
    }


    //添加常用语
    public function add_message()
    {
        $message = $this->request->post('message');
        if (empty($message)) {
            return json(['code' => 1, 'message' => '常用语不能为空！']);
        }
        $result = Db::name('tp_message')
            ->insert(['message' => $message]);

        if ($result) {
            return json(['code' => 0, 'message' => '添加成功，请重新打开当前弹窗页面！']);
        }
        return json(['code' => 1, 'message' => '添加失败！']);
    }

    public function cos_sts()
    {

        // 获取临时密钥，计算签名
        $tempKeys = cossts();
        return json(['code' => 0, 'message' => 'cos鉴权', 'data' => $tempKeys]);

    }

    /**
     *令牌桶任务
     */
    public function token_add()
    {

        $config = RedisClass::get_vote_config_info();
        //开启流量限制
        if ($config['total_limit_status']) {
            $result = TokenBucket::add(10);
            echo $result;
        } else {
            echo '未开启';
        }

    }

}
